package top.jfunc.http.ribbon;

import com.netflix.client.config.DefaultClientConfigImpl;
import com.netflix.config.ConfigurationManager;
import com.netflix.loadbalancer.*;
import top.jfunc.common.utils.Joiner;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class RibbonInit {
    private static final Map<String, BaseLoadBalancer> LOAD_BALANCER_MAP = new HashMap<>();
    public static void init(String clientName, List<Server> servers, IRule iRule, LoadBalancerBuilderCustomizer<Server> customizer){

        ConfigurationBasedServerList serverList = new ConfigurationBasedServerList();
        serverList.initWithNiwsConfig(DefaultClientConfigImpl.getClientConfigWithDefaultValues(clientName));
        ConfigurationManager.getConfigInstance().setProperty(clientName+".ribbon.listOfServers", Joiner.on(",").join(servers));

        LoadBalancerBuilder<Server> builder = LoadBalancerBuilder.newBuilder()
                .withRule(iRule)
                .withDynamicServerList(serverList);

        if(null != customizer){
            customizer.config(builder);
        }

        BaseLoadBalancer lb = builder
                .buildDynamicServerListLoadBalancer();

        ILoadBalancer old = LOAD_BALANCER_MAP.put(clientName, lb);
        if(null != old){
            throw new IllegalArgumentException("exists " + clientName);
        }
    }
    public static void init(String clientName, List<Server> servers){
        init(clientName, servers, new RoundRobinRule(), null);
    }

    public static BaseLoadBalancer get(String clientName){
        return LOAD_BALANCER_MAP.get(clientName);
    }
}
